﻿import React, {Component} from 'react';
import {
	ActivityIndicator,
	Alert,
	FlatList,
	RefreshControl,
	StyleSheet,
	Text,
	TouchableOpacity,
	View,
} from 'react-native';
import BackImage from '../component/BackImage';
import getStyles from '../../style/styles';
import axiosInstance from '../utils/request';


let rows=500;//
let totalPage=0;//总的页数
let itemNo=0;//item的个数

let styles={};
export default class PaidScene extends Component {

	static navigationOptions =({ navigation }) => ({
  		title: '已缴费统计',
		headerStyle: {
		  backgroundColor: 'rgba(0, 191 ,255, 0.5)',
		},
		headerBackImage:<BackImage/>, //使用组件
		headerTintColor: '#fff',
		headerTitleStyle: {
		  fontWeight: 'bold',
		}
  	});

    constructor(props){
		super(props);
		this.state = {
			isConnected: null,
			page:1,
            isLoading: true,
            //网络请求状态
            error: false,
            errorInfo: "",
            dataArray: [],
            showFoot:0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            isRefreshing:false,//下拉控制
	 	};
	}

	//组件挂载完成后执行的方法
    componentDidMount(){
        //组件挂载后开始下载数据
        this.fetchData('');
    }

	/*
		因为服务端modified字段代表的是时间戳，所以Max(anchor)表示客户端最近一次同步的时间，如果存在服务端modified > Max(anchor),
		说明服务端需要向客户端同步数据。
	*/
	fetchData(bookName){
		let URL= global.server.url+'/arrears/selectPaidList';
		if(bookName){
			page=1;
		}else{
			page=this.state.page;
		}
		axiosInstance.post(URL,
			{
				bookName:bookName,
				currMonth:global.user.accountCycle.currMonth,
				pageVO:{
					page:page,
					rows:rows,
					group:'mb.id'
				}
			}
		)
        .then(res => {
			let datas = [];
			let totalYhs=0,totalFact=0;
			totalPage=res.pages;
			datas = datas.concat(res.records);
            let dataBlob = [];//这是创建该数组，目的放存在key值的数据，就不会报黄灯了
            let i = itemNo;
            datas.map(function (item) {
            	dataBlob.push({
                	key: i,
					bookName:item.bookName,
					yhs: item.yhs,
                    sumFact: item.sumFact,
                })
                i++;
				totalYhs+=item.yhs;
				totalFact+=item.sumFact;
            });
            itemNo = i;
            let foot = 0;
            if(this.state.page>=totalPage){
                foot = 1;//listView底部显示没有更多数据了
            }

            this.setState({
                //复制数据源
            	//dataArray:this.state.dataArray.concat( responseData.results),
                dataArray:this.state.dataArray.concat( dataBlob),
                isLoading: false,
                showFoot:foot,
                isRefreshing:false,
				totalYhs:totalYhs,
				totalFact:totalFact
            });
            datas = null;//重置为空
            dataBlob = null;
        })
        .catch(error => {
        	this.setState({
				error: true,
                errorInfo: error
			});
			Alert.alert("网络异常，请稍后再试！");
        })
	}

	shouldComponentUpdate() {
        return true
    }

    handleRefresh = () => {
        this.setState({
            page:1,
            isRefreshing:true,//tag,下拉刷新中，加载完全，就设置成flase
            dataArray:[]
        });
        this.fetchData()
    }

	//加载等待页
    renderLoadingView() {
        return (
            <View style={style.container}>
                <ActivityIndicator
                    animating={true}
                    color='blue'
                    size="large"
                />
            </View>
        );
    }

    _keyExtractor = (item, index) => index;

    //加载失败view
    renderErrorView() {
        return (
            <View style={style.container}>
                <Text>
                    {this.state.errorInfo}
                </Text>
            </View>
        );
    }

	goto = (item) => {
		this.props.navigation.navigate('ArrearsDetailScene', {bookId:item.bookId,bookName:item.bookName})
	}

	renderData() {
		styles=getStyles();
        return (
			<View style={style.container}>
				<View style={{
					height:35,
					flexDirection:'row',
					alignItems:'center',
					borderBottomWidth:1,
					borderBottomColor:'#D7D7D7',
					backgroundColor:"#F5FCFF",
					paddingLeft:6
				}}>
					<View style={styles.flex}>
						<Text style={styles.headerText}>表册名称</Text>
					</View>
					<View style={styles.flex}>
						<Text style={styles.headerText}>已缴户数</Text>
					</View>
					<View style={styles.flex }>
						<Text style={styles.headerText}>已缴金额</Text>
					</View>
				</View>
				<FlatList
					data={this.state.dataArray}
					renderItem = {({item}) =>
						<TouchableOpacity activeOpacity={0.5} >
							<View style={{
								height:35,
								flexDirection:'row',
								alignItems:'center',
								borderBottomWidth:1,
								borderBottomColor:'#D7D7D7',
								paddingLeft:6
							}}>
								<View style={styles.flex}>
									<Text style={styles.headerText}>{item.bookName}</Text>
								</View>
								<View style={styles.flex}>
									<Text style={styles.headerText}>{item.yhs}</Text>
								</View>
								<View style={styles.flex}>
									<Text style={styles.headerText}>{item.sumFact}</Text>
								</View>
							</View>
						</TouchableOpacity>
					}
					ListFooterComponent={this._renderFooter.bind(this)}
					onEndReached={this._onEndReached.bind(this)}
					onEndReachedThreshold={0.1}
					ItemSeparatorComponent={this._separator}
					keyExtractor={this._keyExtractor}
					//为刷新设置颜色
					refreshControl={
						<RefreshControl
							refreshing={this.state.isRefreshing}
							onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
							colors={['#ff0000', '#00ff00','#0000ff','#3ad564']}
							progressBackgroundColor="#ffffff"
						/>
					}
				/>
				<View style={{
					height:35,
					flexDirection:'row',
					alignItems:'center',
					borderBottomWidth:1,
					borderBottomColor:'#D7D7D7',
					backgroundColor:"#F5FCFF",
					paddingLeft:6
				}}>
					<View style={styles.flex}>
						<Text style={styles.headerText}>总户数：{this.state.totalYhs}</Text>
					</View>
					<View style={styles.flex}>
						<Text style={styles.headerText}>已缴金额：{this.state.totalFact}</Text>
					</View>
				</View>
			</View>
        );
    }

    render() {
        //第一次加载等待的view
        if (this.state.isLoading && !this.state.error) {
            return this.renderLoadingView();
        } else if (this.state.error) {
            //请求失败view
            return this.renderErrorView();
        }
        //加载数据
        return this.renderData();
    }

    _separator(){
        return <View style={{height:1,backgroundColor:'#999999'}}/>;
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    _onEndReached(){
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot != 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((this.state.page!=1) && (this.state.page>=totalPage)){
            return;
        } else {
            this.state.page++;
        }
        //底部显示正在加载更多数据
        this.setState({showFoot:2});
        //获取数据，在componentDidMount()已经请求过数据了
    	if (this.state.page>1){
            this.fetchData();
        }
    }
}

const style = StyleSheet.create({
	container: {
        flex: 1,
    },
});

